package com.yzf.smsforward;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.PorterDuff;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.loopeer.cardstack.CardStackView;
import com.loopeer.cardstack.StackAdapter;
import com.yzf.pcsmsforward.R;
import com.yzf.smsforward.utils.Utils;
import com.yzf.smsforward.utils.log.LogcatFileManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import static com.yzf.smsforward.Constants.TAG;
import static com.yzf.smsforward.Constants.versionName;

/**
 * 项目名称：FoldingVerifyCode
 * 类描述：设备信息的适配器
 * 创建人：Administrator
 * 创建时间：2019年10月1日
 */
public class CardAdapter extends StackAdapter<Integer> {

    private Context mContext;
    private static Activity mActivity;
    private static ArrayList<Sms> mList = new ArrayList<>();
    private static com.yzf.smsforward.SMSAdapter adapter;
    //    private static ScrollView mSmsSv;
    private static ListView mSmsLv;
    private static boolean isNeedShowMsg = false;
    private static StackViewHolderMsg msgHolder;
    @SuppressLint("HandlerLeak")
    public static Handler smsHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg == null) {
                return;
            }
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    isNeedShowMsg = true;
                    msgHolder.showContentView();
                }
            });
            final Sms sms = (Sms) msg.obj;
            Log.d(TAG, "------smsHandler--------" + sms);
            if (TextUtils.isEmpty(sms.getIsSave())) {
                showToast("不显示");
                return;
            } else if (sms.getIsSave().equals("1")) {
                Log.d(TAG, "sms.getIsSave()=====" + sms.getIsSave());
                showToast("不显示");
                return;
            }
            Log.d(TAG, "sms.getIsSave()=====" + sms.getIsSave());
            Log.d(TAG, "sms.getIsSave()=====" + sms.getVerifycode());
            if (mList.size() >= 9) {
                mList.remove(0);
            }
            mList.add(sms);
            if (adapter != null) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ArrayList<Sms> mListSms = new ArrayList<>();
                        mListSms.addAll(mList);
                        Collections.reverse(mListSms);
                        adapter.refresh(mListSms);
                        ((CardStackActivity)mActivity).updateMiniList();
                    }
                });
            } else {
                ArrayList<Sms> mListSms = new ArrayList<>();
                mListSms.addAll(mList);
                Collections.reverse(mListSms);
                adapter = new com.yzf.smsforward.SMSAdapter(mActivity, mListSms);
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mSmsLv.setAdapter(adapter);
                        ((CardStackActivity)mActivity).updateMiniList();
                    }
                });
            }
        }
    };

    @SuppressLint("HandlerLeak")
    private static Handler urlHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mActivity.recreate();
                }
            });
        }
    };


    public CardAdapter(Activity activity) {
        super(activity);
        this.mContext = activity.getApplicationContext();
        this.mActivity = activity;
    }

    @Override
    public void bindView(Integer data, int position, CardStackView.ViewHolder holder) {
        if (holder instanceof StackViewHolderSetting) {
            StackViewHolderSetting setting = (StackViewHolderSetting) holder;
            setting.onBind(data, position);
        } else if (holder instanceof StackViewHolderMsg) {
            msgHolder = (StackViewHolderMsg) holder;
            msgHolder.onBind(data, position);
        } else if (holder instanceof StackViewHolderInfo) {
            StackViewHolderInfo info = (StackViewHolderInfo) holder;
            info.onBind(data, position);
        }
    }

    @Override
    protected CardStackView.ViewHolder onCreateView(ViewGroup parent, int viewType) {
        CardStackView.ViewHolder holder = null;
        View view;
        switch (viewType) {
            case R.layout.card_view_info:
                view = getLayoutInflater().inflate(R.layout.card_view_info, parent, false);
                holder = new StackViewHolderInfo(view);
                break;
            case R.layout.card_view_setting:
                view = getLayoutInflater().inflate(R.layout.card_view_setting, parent, false);
                holder = new StackViewHolderSetting(view);
                break;
            case R.layout.card_view_msg:
                view = getLayoutInflater().inflate(R.layout.card_view_msg, parent, false);
                holder = new StackViewHolderMsg(view);
                break;

        }
        return holder;
    }

    @Override
    public int getItemViewType(int position) {
        int type;
        switch (position) {
            case 0:
                type = R.layout.card_view_info;
                break;
            case 1:
                type = R.layout.card_view_setting;
                break;
            case 2:
                type = R.layout.card_view_msg;
                break;
            default:
                type = R.layout.card_view_info;
                break;
        }
        return type;
    }

    class StackViewHolderSetting extends CardStackView.ViewHolder {
        View mLayout;
        TextView mTitleView;
        View mContentView;
        TextView mUrlInfo;
        TextView mPhoneInfo;
        TextView mTV_matching_rules;
        View mUrlSetting;
        View mPhoneSetting;
        View mRL_matching_rules;

        public StackViewHolderSetting(View view) {
            super(view);
            this.mLayout = view.findViewById(R.id.frame_list_card_item);
            this.mTitleView = view.findViewById(R.id.text_list_card_title);
            this.mContentView = view.findViewById(R.id.container_list_content);
            this.mUrlInfo = view.findViewById(R.id.url_info_setting);
            this.mPhoneInfo = view.findViewById(R.id.phone_info_setting);
            this.mTV_matching_rules = view.findViewById(R.id.mTV_matching_rules);
            mUrlSetting = view.findViewById(R.id.card_setting_url);
            mPhoneSetting = view.findViewById(R.id.card_setting_phone);
            mRL_matching_rules = view.findViewById(R.id.mRL_matching_rules);
        }

        @Override
        public void onItemExpand(boolean b) {
            mContentView.setVisibility(b ? View.VISIBLE : View.GONE);
            String phoneStr = "手机号码信息\n\n";
            if (com.yzf.smsforward.Constants.numbers.size() == 1) {
                phoneStr = phoneStr + "手机卡1号码：" + com.yzf.smsforward.Constants.numbers.get(com.yzf.smsforward.Constants.TEL1_KEY);
            } else if (com.yzf.smsforward.Constants.numbers.size() == 2) {
                phoneStr = phoneStr + "手机卡1号码：" + com.yzf.smsforward.Constants.numbers.get(com.yzf.smsforward.Constants.TEL1_KEY);
                phoneStr =
                        phoneStr + "\n\n手机卡2号码：" + com.yzf.smsforward.Constants.numbers.get(com.yzf.smsforward.Constants.TEL2_KEY);
            } else {
                Log.d(TAG, "Constants.numbers = " + com.yzf.smsforward.Constants.numbers.toString());
            }
            mPhoneInfo.setText(phoneStr);
        }

        @Override
        protected void onAnimationStateChange(int state, boolean willBeSelect) {
            super.onAnimationStateChange(state, willBeSelect);
        }

        public void onBind(Integer data, int position) {
            Log.d(TAG, "StackViewHolderSetting ===> " + data);
            mLayout.getBackground().setColorFilter(ContextCompat.getColor(getContext(), data), PorterDuff.Mode.SRC_IN);
            mTitleView.setText(com.yzf.smsforward.Constants.TITLESTRS[position]);
            String urlStr = "URL地址\n\n";
            urlStr = urlStr + Utils.getValueFromSP(mContext, com.yzf.smsforward.Constants.HTTPS_URL,
                    com.yzf.smsforward.Constants.HTTPS_URL_KEY);
            mUrlInfo.setText(urlStr);
            Constants.MATCHING_RULES_STRING = Utils.getValueFromSP(mContext, com.yzf.smsforward.Constants.MATCHING_RULES,
                    com.yzf.smsforward.Constants.MATCHING_RULES);
            if (TextUtils.isEmpty(Constants.MATCHING_RULES_STRING)) {
            } else {
                Constants.matching_rules_array = Constants.MATCHING_RULES_STRING.split("/");
                mTV_matching_rules.setText(Constants.MATCHING_RULES_STRING);
            }

            mUrlSetting.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    com.yzf.smsforward.UrlDialog dialog = new com.yzf.smsforward.UrlDialog(mActivity, urlHander, "");
                    if (!dialog.isShowing()) {
                        dialog.show();
                    }
                }
            });
            mPhoneSetting.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TelDialog dialog = new TelDialog(mActivity);
                    if (!dialog.isShowing()) {
                        dialog.show();
                    }
                }
            });
            mRL_matching_rules.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MatchingRulesDialog dialog = new MatchingRulesDialog(mActivity, urlHander,
                            new MatchingRulesDialog.MatchingRules() {
                                @Override
                                public void backMatchingRules(String matchingRules) {
                                    Log.d("luohao", "matchingRules------" + matchingRules);
                                    Constants.MATCHING_RULES_STRING = matchingRules;
                                    if (TextUtils.isEmpty(Constants.MATCHING_RULES_STRING)) {
                                        matchingRules = "无匹配规则...";
                                        Constants.matching_rules_array = new String[]{};
                                    }
                                    mTV_matching_rules.setText(matchingRules);
                                }
                            });
                    if (!dialog.isShowing()) {
                        dialog.show();
                    }
                }
            });
        }
    }

    class StackViewHolderMsg extends CardStackView.ViewHolder {
        View mLayout;
        TextView mTitleView;
        //        ScrollView mSmsSv;
        View mContentView;

        public StackViewHolderMsg(View view) {
            super(view);
            this.mLayout = view.findViewById(R.id.frame_list_card_item);
            this.mTitleView = view.findViewById(R.id.text_list_card_title);
            mContentView = view.findViewById(R.id.container_list_content);
            //            mSmsSv = view.findViewById(R.id.sms_sv);
            mSmsLv = view.findViewById(R.id.sms_ls);
        }

        public void showContentView() {
            mContentView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onItemExpand(boolean b) {
            if (!isNeedShowMsg) {
                mContentView.setVisibility(b ? View.VISIBLE : View.GONE);
            }
        }

        @Override
        protected void onAnimationStateChange(int state, boolean willBeSelect) {
            super.onAnimationStateChange(state, willBeSelect);
        }

        public void onBind(Integer data, int postion) {
            mLayout.getBackground().setColorFilter(ContextCompat.getColor(getContext(), data), PorterDuff.Mode.SRC_IN);
            mTitleView.setText(com.yzf.smsforward.Constants.TITLESTRS[postion]);
            mSmsLv.setAdapter(new com.yzf.smsforward.SMSAdapter(mActivity, mList));
        }
    }

    class StackViewHolderInfo extends CardStackView.ViewHolder {
        View mLayout;
        TextView mTitleView;
        View mContentView;
        TextView mPhoneInfoTv;
        TextView mSim1InfoTv;
        TextView mSim2InfoTv;
        TextView mLogPathTv;
        TextView mVersionInfoTv;

        public StackViewHolderInfo(View view) {
            super(view);
            this.mLayout = view.findViewById(R.id.frame_list_card_item);
            this.mTitleView = view.findViewById(R.id.text_list_card_title);
            this.mContentView = view.findViewById(R.id.container_list_content);
            this.mPhoneInfoTv = view.findViewById(R.id.phone_info_tv);
            this.mSim1InfoTv = view.findViewById(R.id.sim1_info_tv);
            this.mSim2InfoTv = view.findViewById(R.id.sim2_info_tv);
            mLogPathTv = view.findViewById(R.id.log_path_setting_tv);
            mVersionInfoTv = view.findViewById(R.id.version_info_tv);
        }

        @Override
        public void onItemExpand(boolean b) {
            mContentView.setVisibility(b ? View.VISIBLE : View.GONE);
            TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            JSONArray array = com.yzf.smsforward.SimUtils.getSimInfoBySubscriptionManager(mContext);
            String imei = Utils.getSerialNumber();
            String imsi = tm.getSubscriberId();
            Log.d(TAG, "IMEI = " + imei);
            Log.d(TAG, "IMSI = " + imsi);
            mPhoneInfoTv.setText("设备id: " + imei
                    //                    + "\n\n" + "安卓id: " + imsi
            );
            String infoStr = "";
            String infoStr2 = "";
            if (array.length() == 1) {
                mSim2InfoTv.setVisibility(View.GONE);
                try {
                    JSONObject json = array.getJSONObject(0);
                    infoStr = "SIM 卡1信息";
                    infoStr = infoStr +
                            "\n\n手机号码：" + com.yzf.smsforward.Constants.numbers.get(com.yzf.smsforward.Constants.TEL1_KEY) +
                            "\n运营商：" + array.getJSONObject(0).getString(com.yzf.smsforward.Constants.CARRIERNAME) +
                            "\nsubId：" + json.getString(com.yzf.smsforward.Constants.SUBID) +
                            "\nsimSlotIndex：" + json.getString(com.yzf.smsforward.Constants.SIMSLOTINDEX) +
                            "\ndisplayName：" + json.getString(com.yzf.smsforward.Constants.DISPLAYNAME) +
                            "\nSubscriberId：" + json.getString(com.yzf.smsforward.Constants.SUBSCRIBER_ID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mSim1InfoTv.setText(infoStr);
            } else if (array.length() == 2) {
                mSim2InfoTv.setVisibility(View.VISIBLE);
                try {
                    JSONObject json = array.getJSONObject(0);
                    infoStr = "SIM 卡1信息";
                    infoStr = infoStr +
                            "\n\n手机号码：" + com.yzf.smsforward.Constants.numbers.get(com.yzf.smsforward.Constants.TEL1_KEY) +
                            "\n运营商：" + array.getJSONObject(0).getString(com.yzf.smsforward.Constants.CARRIERNAME) +
                            "\nsubId：" + json.getString(com.yzf.smsforward.Constants.SUBID) +
                            "\nsimSlotIndex：" + json.getString(com.yzf.smsforward.Constants.SIMSLOTINDEX) +
                            "\ndisplayName：" + json.getString(com.yzf.smsforward.Constants.DISPLAYNAME) +
                            "\nSubscriberId：" + json.getString(com.yzf.smsforward.Constants.SUBSCRIBER_ID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    JSONObject json2 = array.getJSONObject(1);
                    infoStr2 = "SIM 卡2信息";
                    infoStr2 = infoStr2 +
                            "\n\n手机号码：" + com.yzf.smsforward.Constants.numbers.get(com.yzf.smsforward.Constants.TEL2_KEY) +
                            "\n运营商：" + array.getJSONObject(1).getString(com.yzf.smsforward.Constants.CARRIERNAME) +
                            "\nsubId：" + json2.getString(com.yzf.smsforward.Constants.SUBID) +
                            "\nsimSlotIndex：" + json2.getString(com.yzf.smsforward.Constants.SIMSLOTINDEX) +
                            "\ndisplayName：" + json2.getString(com.yzf.smsforward.Constants.DISPLAYNAME) +
                            "\nSubscriberId：" + json2.getString(com.yzf.smsforward.Constants.SUBSCRIBER_ID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mSim1InfoTv.setText(infoStr);
                mSim2InfoTv.setText(infoStr2);

            }
        }

        @Override
        protected void onAnimationStateChange(int state, boolean willBeSelect) {
            super.onAnimationStateChange(state, willBeSelect);
        }

        public void onBind(Integer data, int postion) {
            mLayout.getBackground().setColorFilter(ContextCompat.getColor(getContext(), data), PorterDuff.Mode.SRC_IN);
            mTitleView.setText(com.yzf.smsforward.Constants.TITLESTRS[postion]);
            String logPath = "日志地址";
            String logPathSp = Utils.getValueFromSP(mContext, com.yzf.smsforward.Constants.LOGPATH_SP,
                    com.yzf.smsforward.Constants.LOGPATH_SP_KEY);
            if (!TextUtils.isEmpty(logPathSp)) {
                logPath = logPath + "\n\n" + logPathSp;
            }
            mLogPathTv.setText(logPath);
            mVersionInfoTv.setText("应用版本号\n\n" + versionName);
        }
    }

    public static ArrayList<Sms> getList() {
        return mList;
    }

    private ArrayList<Sms> sortList(List<Sms> list) {
        ArrayList<Sms> resultList = new ArrayList<Sms>();
        int size = list.size();
        for (int i = 0; i < list.size(); i++) {
            resultList.add(list.get(size - 1 - i));
        }
        return resultList;
    }

    private static void showToast(final String msg) {
        LogcatFileManager.showToast(mActivity.getBaseContext(), msg);

    }

}
